package com.cherry.androidcode.third

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.alipay.sdk.app.AuthTask
import com.alipay.sdk.app.PayTask
import com.cherry.androidcode.AppConstant.WX_APP_ID
import com.cherry.androidcode.AppConstant.WX_APP_SECRET
import com.cherry.androidcode.R
import com.cherry.androidcode.util.bitmap2ByteArray
import com.ilaisa.laishang.*
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.*
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * @author DongMS
 * @since 2020/4/10
 */
class ThirdActivity : AppCompatActivity() {

    private lateinit var mUmShareAPI: UMShareAPI

    private val shareListener by lazy {
        //注意微信已经不支持分享回调了
        object : UMShareListener {
            override fun onResult(p0: SHARE_MEDIA?) {
                Log.e("umeng_auth", "平台：${p0?.toString()}")
                Toast.makeText(applicationContext, "分享成功", Toast.LENGTH_LONG).show()
            }

            override fun onCancel(p0: SHARE_MEDIA?) {
                Toast.makeText(applicationContext, "分享取消", Toast.LENGTH_LONG).show()
            }

            override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                Log.e("umeng_auth", "平台：${p0?.toString()},${p1?.message}")
                Toast.makeText(applicationContext, "分享失败", Toast.LENGTH_LONG).show()
            }

            override fun onStart(p0: SHARE_MEDIA?) {
            }
        }
    }

    private val authListener by lazy {
        object : UMAuthListener {
            override fun onCancel(p0: SHARE_MEDIA?, p1: Int) {
                Toast.makeText(applicationContext, "授权取消", Toast.LENGTH_LONG).show()
            }

            override fun onError(p0: SHARE_MEDIA?, p1: Int, p2: Throwable?) {
                Log.e("umeng_auth", p2?.message ?: "")
                Toast.makeText(applicationContext, "授权失败", Toast.LENGTH_LONG).show()
            }

            override fun onStart(p0: SHARE_MEDIA?) {
            }

            /**
             * 各个字段定义参考 https://developer.umeng.com/docs/66632/detail/66639#h2-u7B2Cu4E09u65B9u767Bu5F5514
             */
            override fun onComplete(p0: SHARE_MEDIA?, p1: Int, p2: MutableMap<String, String>?) {
                Toast.makeText(applicationContext, "授权成功", Toast.LENGTH_LONG).show()
                Log.e("umeng_auth", "平台：$p0,用户信息:${p2?.onEach { it.key + "\t" + it.value + "\n" }}")
            }

        }
    }

    private val wxapi by lazy {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例，第三个参数是否检查签名
        WXAPIFactory.createWXAPI(this, WX_APP_ID, true)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third)
        umengConfig()
    }

    private fun umengConfig() {
        UMConfigure.init(this, "xxxxx", "channel", UMConfigure.DEVICE_TYPE_PHONE, null)
        UMConfigure.setLogEnabled(true)
        PlatformConfig.setAlipay("xxxxxxx")
        PlatformConfig.setSinaWeibo("xxxxxxxxx", "xxxxxxxxxx", "https://api.weibo.com/oauth2/default.html")
        PlatformConfig.setWeixin(WX_APP_ID, WX_APP_SECRET)
        PlatformConfig.setQQZone("xxxxxxxx", "xxxxxxxxxx")

        mUmShareAPI = UMShareAPI.get(this)
        val config = UMShareConfig()
        config.isNeedAuthOnGetUserInfo(true)
        mUmShareAPI.setShareConfig(config)
    }

    private fun generateOrder(isWx: Boolean, payOrderSuccess: (OrderPayResult, OrderPayReq?) -> Unit) {
        payOrderSuccess(OrderPayResult(1, "", null), null)
    }

    private fun generateALiAuth(aliAuth: (authStr: String) -> Unit) {
        aliAuth("")
    }

    ////友盟/////
    fun umengLogin(view: View) {
        showDialog(true)
    }

    fun umengShare(view: View) {
        showDialog(false)
    }

    fun showDialog(isAuth: Boolean) {
        val dialogView = View.inflate(this, R.layout.dialog_umeng, null)
        dialogView.findViewById<TextView>(R.id.tv_ali).setOnClickListener {
            if (isAuth) {
                //ALIPAY[SA10000]平台不支持授权,无法完成操作，自己定义了。。。
                //mUmShareAPI.getPlatformInfo(this, SHARE_MEDIA.ALIPAY, authListener)
                aliLogin(dialogView)
            } else {
                umengWebShareTo(SHARE_MEDIA.ALIPAY)
            }
        }
        dialogView.findViewById<TextView>(R.id.tv_qq).setOnClickListener {
            //todo qq分享需要做权限适配
            if (!mUmShareAPI.isInstall(this, SHARE_MEDIA.QQ)) {
                Toast.makeText(applicationContext, "没有安装qq", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (isAuth) {
                mUmShareAPI.getPlatformInfo(this, SHARE_MEDIA.QQ, authListener)
            } else {
                umengWebShareTo(SHARE_MEDIA.QQ)
            }

        }
        dialogView.findViewById<TextView>(R.id.tv_wechat).setOnClickListener {
            if (!mUmShareAPI.isInstall(this, SHARE_MEDIA.WEIXIN)) {
                Toast.makeText(applicationContext, "没有安装微信", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (isAuth) {
                mUmShareAPI.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener)
            } else {
                //SHARE_MEDIA.WEIXIN_CIRCLE  微信朋友圈
                umengWebShareTo(SHARE_MEDIA.WEIXIN)
            }
        }
        dialogView.findViewById<TextView>(R.id.tv_weibo).setOnClickListener {
            if (isAuth) {
                mUmShareAPI.getPlatformInfo(this, SHARE_MEDIA.SINA, authListener)
            } else {
                umengWebShareTo(SHARE_MEDIA.SINA)
            }
        }
        AlertDialog.Builder(this)
                .setView(dialogView)
                .create()
                .show()
    }

    private fun umengWebShareTo(media: SHARE_MEDIA) {
        val web = UMWeb("https://www.baidu.com")
        web.title = "分享标题"
        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
        val thumbBmp = Bitmap.createScaledBitmap(bitmap, 50, 50, true)
        bitmap.recycle()
        web.setThumb(UMImage(this, thumbBmp))  //缩略图
        web.description = "分享内容"
        ShareAction(this)
//                .withMedia(UMImage())
                .setPlatform(media)//传入平台
                .withMedia(web)//分享内容
                .setCallback(shareListener)//回调监听器
                .share()
    }

    //QQ与新浪不需要添加Activity，但需要在使用QQ分享或者授权的Activity中，添加.注意onActivityResult不可在fragment中实现，如果在fragment中调用登录或分享，需要在fragment依赖的Activity中实现
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    ////支付宝///

    fun aliPay(view: View) {
        generateOrder(false) { result, payInfo ->

            if (payInfo == null) {
                Toast.makeText(applicationContext, result.info, Toast.LENGTH_SHORT).show()
                return@generateOrder
            }
            //需要判断有安装支付宝？？？
            Observable.just(payInfo)
                    .map {
                        val aliPayResult = AliPayResult(PayTask(this@ThirdActivity).payV2(it.orderStr, true))
                        if (!aliPayResult.paySuccess) {
                            Log.e("ali_pay", aliPayResult.toString())
                            throw AliException(aliPayResult.resultStatus, aliPayResult.memo)
                        }
                        aliPayResult
                    }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Toast.makeText(this@ThirdActivity, "支付宝支付成功", Toast.LENGTH_SHORT).show()
                    }, {
                        //商户客户端会收到详细错误信息，包含具体错误码以及错误描述（注意：支付宝 App弹窗提示中的错误文案，为用户视角所看到的错误信息，不可用于开发者视角用于排查问题的依据）
                        if (it is AliException) {
                            Toast.makeText(this@ThirdActivity, "${it.errorMsg}", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(this@ThirdActivity, "支付宝支付失败", Toast.LENGTH_SHORT).show()
                        }
                    })
        }
    }


    fun aliLogin(view: View) {
        //授权链接需要商户服务器请求获取
        generateALiAuth { str ->
            Observable.just(str)
                    .map {
                        val result = ALiAuthResult(AuthTask(this@ThirdActivity).authV2(it, true))
                        if (!result.authSuccess) {
                            Log.e("ali_pay", result.toString())
                            throw AliException(result.resultStatus, result.memo)
                        }
                        result
                    }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Log.e("ali_pay", it.toString())
                        Toast.makeText(this@ThirdActivity, "支付宝授权成功", Toast.LENGTH_SHORT).show()
                        //todo 再次调用商户服务器接口将授权的信息回传
                    }, {
                        //取消居然会提示支付未完成
//                        if (it is AliException) {
//                            Toast.makeText(this@ThirdActivity, "${it.errorMsg}", Toast.LENGTH_SHORT).show()
//                        } else {
                        Toast.makeText(this@ThirdActivity, "支付宝授权失败", Toast.LENGTH_SHORT).show()
//                        }
                    })
        }
    }


    fun aliShare(view: View) {

    }


    //////微信//////

    fun wechatPay(view: View) {
        //商户服务器生成支付订单，先调用统一下单API生成预付单，获取到prepay_id后将参数再次签名传输给APP发起支付
        generateOrder(true) { result, payInfo ->

            if (payInfo == null) {
                Toast.makeText(applicationContext, result.info, Toast.LENGTH_SHORT).show()
                return@generateOrder
            }

            if (!wxapi.isWXAppInstalled) {
                //引导用户安装微信
                return@generateOrder
            }
            val req = PayReq().apply {
                //APP端调起支付的参数列表
                //https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2
                appId = payInfo.appid
                partnerId = payInfo.partnerid
                prepayId = payInfo.prepayid
                packageValue = "Sign=WXPay"
                nonceStr = payInfo.noncestr
                timeStamp = payInfo.timestamp
                sign = payInfo.sign
            }
            wxapi.sendReq(req)
        }
    }


    fun wechatLogin(view: View) {
        if (!wxapi.isWXAppInstalled) {
            //引导用户安装微信
            return
        }
        val req = SendAuth.Req().apply {
            scope = "snsapi_userinfo"//获取用户个人信息则填写snsapi_userinfo
//            state = "随便，可选"用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止 csrf 攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加 session 进行校验
        }
        wxapi.sendReq(req)
    }

    //分享需要存储权限，sdk内部已经做适配
    fun wechatShare(view: View) {
        if (!wxapi.isWXAppInstalled) {
            //引导用户安装微信
            return
        }
        val req = SendMessageToWX.Req().apply {
            //分享到对话:
            //SendMessageToWX.Req.WXSceneSession
            //分享到朋友圈:
            //SendMessageToWX.Req.WXSceneTimeline ;
            //分享到收藏:
            //SendMessageToWX.Req.WXSceneFavorite
            scene = SendMessageToWX.Req.WXSceneSession
            //对应该请求的事务 ID，通常由 Req 发起，回复 Resp 时应填入对应事务 ID
            transaction = System.currentTimeMillis().toString()
//            message = shareWxImg()
            message = shareWxWeb()
        }
        wxapi.sendReq(req)
    }

    /**
     * 分享一个网页
     */
    private fun shareWxWeb() = WXMediaMessage(WXWebpageObject("https://www.baidu.com")).apply {
        title = "分享标题"
        description = "分享内容"
        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
        val thumbBmp = Bitmap.createScaledBitmap(bitmap, 50, 50, true)
        bitmap.recycle()
        //缩略图
        thumbData = thumbBmp.bitmap2ByteArray()
    }

    /**
     *  分享一张图片
     */
    private fun shareWxImg() = WXMediaMessage().apply {
        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
        //图片
        mediaObject = WXImageObject(bitmap)
        val thumbBmp = Bitmap.createScaledBitmap(bitmap, 50, 50, true)
        bitmap.recycle()
        //缩略图
        thumbData = thumbBmp.bitmap2ByteArray()
    }
}